<?php
        
    /*
    * 畅远科技签名
    */
    function payChangyuanSign($list, $md5key) {
       ksort($list);
       $md5str = '';
       foreach ($list as $key => $val) {
           if(!empty($val)){
               $md5str = $md5str . $key . '=' . $val . '&';
           }
       }
       $sign = strtoupper(md5($md5str . 'key=' . $md5key));
       return $sign;
    }
    
    /*
     * 下单成功返回
     */
    function payOrderTrue($mchntId, $orderId, $notifyUrl, $transAmt, $uniqueOrderNo, $codeUrl, $md5key) { 
        $resArr = array(
            'code'          => '1000',           // 状态码
            'msg'           => '下单成功',        // 信息
            'merchant_id'   => $mchntId,         // 商户号
            'mchnt_orderid' => $orderId,         // 商户订单号
            'notify_url'    => $notifyUrl,       // 商户通知地址
            'pay_amount'    => $transAmt,        // 金额
            'pay_orderid'   => $uniqueOrderNo,   // 系统单号
            'code_url'      => $codeUrl          // 支付地址
        );
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }
    
    /*
     * 成功支付通知/异步通知返回信息
     */
    function callbackTrue($data, $md5key) {
        $resArr = array(
            'code'          => '1000',
            'bank_trxid'    => $data['bank_trxid'],          // 流水号
            'mchnt_orderid' => $data['mchnt_orderid'],       // 商户订单号
            'pay_orderid'   => $data['pay_orderid'],         // 系统订单号
            'merchant_id'   => $data['merchant_id'],        // 商户号
            'pay_amount'    => $data['pay_amount'] * 100,    // 订单金额
            'actual_amount' => $data['actual_amount'] * 100, // 实际到帐金额
            'payment_time'  => $data['payment_time'],        // 完成时间
            'platform_type' => $data['platform_type'],       // 支付类型
        );
        // 生成新的签名
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }
    
    /*
     * 订单查询返回
     */
     function orderQueryTrue($data, $md5key) {
        $resArr = array(
            'merchant_id'     => $data['merchant_id'],       // model('PayBis')中的商户号
            'mchnt_orderid'   => $data['mchnt_orderid'],      // 商户订单号
            'pay_orderid'     => $data['pay_orderid'],        // 平台订单号
            'pay_amount'      => $data['pay_amount'],         // 交易金额
            'actual_amount'   => $data['actual_amount'],      // 实际到帐金额
            'status'          => $data['status'],             // 订单状态码, 状态识别model('PayStatus')
            'is_notice'       => $data['is_notice'],          // 付款后通知状态
        );
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }
    
    /*
     * 畅远审核客户端代付申请后，向支付平台发起代付请求的返回
     */
     function adminDaifuTrue($resPayDaifuApply) {
        $resArr = array(
            'code'            => '1000',
            'msg'             => '代付请求成功',
            'merchant_id'     => $resPayDaifuApply->merchant_id,       // model('PayBis')中的商户号
            'mchnt_orderid'   => $resPayDaifuApply->mchnt_orderid,      // 商户订单号
            'amount'          => $resPayDaifuApply->amount,            // 交易金额
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 畅远向支付平台发起代付查询请求的返回
     */
     function adminDaifuQueryTrue($resPayDaifuApply) {
        $resArr = array(
            'code'            => '1000',
            'msg'             => $resPayDaifuApply->remark,
            'merchant_id'     => $resPayDaifuApply->merchant_id,       // model('PayBis')中的商户号
            'mchnt_batchid'   => $resPayDaifuApply->mchnt_batchid,    // 出款批次号
            'mchnt_orderid'   => $resPayDaifuApply->mchnt_orderid,    // 出款订单号
            'amount'          => $resPayDaifuApply->amount,            // 交易金额
            'status'          => $resPayDaifuApply->status,
            'bank_status'     => $resPayDaifuApply->bank_status,
            'is_notice'       => $resPayDaifuApply->is_notice,
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 客户端向畅远发起代付请求的返回
     */
    function daifuApplyTrue($dataArr, $md5key) {
        $resArr = array(
            'code'            => '1000',
            'msg'             => '出款请求成功',
            'merchant_id'     => $dataArr['merchant_id'],       // model('PayBis')中的商户号
            'mchnt_orderid'   => $dataArr['mchnt_orderid'],      // 商户订单号
            'amount'          => $dataArr['amount'],         // 交易金额
        );
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }
    
    /*
     * 客户端向畅远发起代付余额查询请求的返回
     */
    function daifuYuETrue($dataArr, $md5key) {
        $resArr = array(
            'code'            => '1000',
            'msg'             => '余额查询成功',
            'merchant_id'     => $dataArr['merchant_id'],     // model('PayBis')中的商户号
            'amount'          => $dataArr['amount'],           // 金额
            'djamount'        => $dataArr['djamount'],         // 冻结金额（注意：正在处理中的金额会写入冻结金额）
        );
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }
    
    /*
     * 客户端向畅远发起代付订单查询请求的返回
     */
    function daifuQueryTrue($dataArr, $md5key) {
        $resArr = array(
            'code'            => '1000',
            'msg'             => $dataArr['msg'],
            'merchant_id'     => $dataArr['merchant_id'],     // model('PayBis')中的商户号
            'mchnt_batchid'   => $dataArr['mchnt_batchid'],    // 出款批次号
            'mchnt_orderid'   => $dataArr['mchnt_orderid'],    // 出款订单号
            'status'          => $dataArr['status'],
            'bank_status'     => $dataArr['bank_status'],
            'is_notice'       => $dataArr['is_notice'],
        );
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }
    
    /*
     * 商户号不存在
     */
    function paymchntIdFalse() {
        $resArr = array(
            'code' => '1001',
            'msg'  => '商户号不存在'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 签名验证失败返回
     */
    function changyuanSignFalse() {
        $resArr = array(
            'code' => '1002',
            'msg'  => '签名验证失败'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 支付平台内部签名验证失败
     */
    function paySignFalse() {
        $resArr = array(
            'code' => '1003',
            'msg'  => '支付平台内部签名验证失败'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 支付通道使用费不足返回
     */
    function payToollFeeFalse() {
        $resArr = array(
            'code' => '1004',
            'msg'  => '支付通道使用费不足，请及时充值'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 订单号已存在，请勿重复下单
     */
    function orderAddFalse() {
        $resArr = array(
            'code' => '1005',
            'msg'  => '订单号已存在，请勿重复下单'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 订单号不存在
     */
    function orderidFalse() {
        $resArr = array(
            'code' => '1006',
            'msg'  => '订单号不存在'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 系统异常
     */
    function systemFalse() {
        $resArr = array(
            'code' => '1007',
            'msg'  => '系统异常，请联系畅远技术支持0753-3312399'
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 下单失败等等情况下，返回错误信息或状态信息
     */
    function retMsgFalse($msg) {
        $resArr = array(
            'code'  => false,
            'msg'   => $msg,
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 代付手续费等等情况下，返回信息或状态信息
     */
    function retMsgTrue($msg) {
        $resArr = array(
            'code'  => true,
            'msg'   => $msg,
        );
        return json_encode($resArr, 320);
    }
    
    /*
     * 订单信息添加
     */
    function payBisOrderAdd($orderData, $payOrderUrl) {
        $data = json_decode($orderData, true);
        $orderDataArr = array(
            'pay_orderid'     => $data['pay_orderid'],      // 平台订单号
            'mchnt_orderid'   => $data['mchnt_orderid'],    // 商户订单号
            'merchant_id'     => $data['merchant_id'],     // 商户号
            'pay_amount'      => $data['pay_amount'],       // 交易金额
            'pay_tradetype'   => $data['pay_tradetype'],    // 支付通道
            'timeout_express' => $data['timeout_express'],  // 订单有效时长
            'pay_orderurl'    => $payOrderUrl,              // 异步回调通知地址
            'pay_callbackurl' => $data['pay_callbackurl'],  // 异步回调通知地址
        );
        model('PayBisOrder')->add($orderDataArr);
    }
    
    /*
     * 更新订单支付状态
     */
    function payBisOrderUpdate($id, $payFee, $mchntFee, $actualAmount) {
        $updateStatus = [
            'pay_fee'        => $payFee,                   // 平台手续费
            'mchnt_fee'      => $mchntFee,                 // 商户手续费
            'actual_amount'  => $actualAmount,       // 实际到帐金额
            'payment_time'   => time(),
            'status'         => 2,  // 1处理中，2支付成功，3订单关闭，4订单超时，5订单拒绝，6订单撤销，7订单取消，8冲正
            'is_notice'      => 0   // 0未通知 1已通知
        ];
        model('PayBisOrder')->updateById($updateStatus, $id);
    }
    
    /*
     * 订单状态
     */
    function orderStatus($status, $id) {
        switch ($status) { // 订单状态
            case 'PROCESSING': // 处理中
                $newData['status'] = 1;
                break;
            case 'SUCCESS': // 订单成功
                $newData['status'] = 2;
                break;
            case 'CLOSED': // 订单关闭
                $newData['status'] = 3;
                break;
            case 'TIME_OUT': // 订单超时
                $newData['status'] = 4;
                break;
            case 'REJECT': // 订单拒绝
                $newData['status'] = 5;
                break;
            case 'REPEALED': // 订单撤销（分账订单退款后查询）
                $newData['status'] = 6;
                break;
            case 'REVOKED': // 订单取消
                $newData['status'] = 7;
                break;
            case 'REVERSAL': // 冲正
                $newData['status'] = 8;
                break;
        }
        model('PayBisOrder')->updateById($newData, $id);
    }
    
    
    /*
     * 客户端向畅远发起代付请求时更新 model('payBis') 相关金额
     */
    function payBisAmount($resPayBis, $amountAndFee) {
        $payBis['djamount'] = $resPayBis->djamount + $amountAndFee;
        $payBis['amount']   = $resPayBis->amount - $amountAndFee;
        $retPayBis          = model('payBis')->updateById($payBis, $resPayBis->id);
        if($retPayBis) {
            return true;
        } 
    }
    
    /*
     * 畅远后台拒绝代付请求 
     */
    function payDaifuRefuse($resPayBis, $resPayDaifuApply) {
        $amountAndFee = $resPayDaifuApply->amount + $resPayDaifuApply->fee;
        $payBisData = array(
            'amount'   => $resPayBis->amount + $amountAndFee,
            'djamount' => $resPayBis->djamount - $amountAndFee,
        );
        $retPayBis = model('PayBis')->updateById($payBisData, $resPayBis->id);
        $payDaifuApply = array(
            'is_agree'    => 2, // 已审核未通过
        );
        $retPayDaifuApply = model('PayDaifuApply')->updateById($payDaifuApply, $resPayDaifuApply->id);
        if($retPayBis && $retPayDaifuApply) {
            return true;
        }
    }
    
    /*
     * 由畅远向支付平台发起代付申请时，更新 model('PayDaifuApply') 中'is_agree'的状态
     */
    function PayDaifuApplyAgree($id, $code) {
        $payDaifuApply['is_agree'] = $code;
        $retPayDaifuApply = model('PayDaifuApply')->updateById($payDaifuApply, $id);
        if($retPayDaifuApply) {
            return true;
        } 
    }
    
    /*
     * 代付打款成功后, 更新商户金额数据等 
     */
    function payBisRemitSuccess($resPayBis, $resPayPlatform, $resPayDaifuApply) {
        $amountAndFee = $resPayDaifuApply->amount + $resPayBis->mchnt_daifu_fee + $resPayPlatform->daifu_fee;
        $payBisData = array(
            'platform_amount' => $resPayBis->platform_amount - $resPayDaifuApply->amount - $resPayPlatform->daifu_fee,
            'djamount'        => $resPayBis->djamount - $amountAndFee,
        );
        $retPayBis = model('PayBis')->updateById($payBisData, $resPayBis->id);
        $payDaifuApply = array(
            'status'      => 1, // 打款状态(0已接收 1已汇出 2已退款 3已拒绝 4待复核 5未知)
            'bank_status' => 'S', // 银行处理状态(S已成功 I银行处理中 F出款失败 W未出款 U未知)
        );
        $retPayDaifuApply = model('PayDaifuApply')->updateById($payDaifuApply, $resPayDaifuApply->id);
        if($retPayBis && $retPayDaifuApply) {
            return true;
        } 
    }
    
    /*
     * 代付打款，银行处理中 出款失败 未出款  未知
     */
    function payBisRemitIFWU($resPayDaifuApply, $bankStatus, $bankMsg) {
        $payDaifuApply = array(
            'status'      => 1, // 打款状态(0已接收 1已汇出 2已退款 3已拒绝 4待复核 5未知)
            'bank_status' => $bankStatus, // 银行处理状态(S已成功 I银行处理中 F出款失败 W未出款 U未知)
            'remark'      => $bankMsg
        );
        $retPayDaifuApply = model('PayDaifuApply')->updateById($payDaifuApply, $resPayDaifuApply->id);
        if($retPayDaifuApply) {
            return true;
        }
    }
    
    /*
     * 代付出款失败后退款处理，已退款
     */
    function payBisRefund($resPayBis, $resPayPlatform, $resPayDaifuApply) {
        $amountAndFee = $resPayDaifuApply->amount + $resPayBis->mchnt_daifu_fee + $resPayPlatform->daifu_fee;
        $payBisData = array(
            'platform_amount' => $resPayBis->platform_amount + $resPayDaifuApply->amount, // 手续费不返还
            'djamount'        => $resPayBis->djamount - $amountAndFee,
        );
        $retPayBis = model('PayBis')->updateById($payBisData,$resPayBis->id);
        $payDaifuApply = array(
            'status'      => 2, // 打款状态(0已接收 1已汇出 2已退款 3已拒绝 4待复核 5未知)
        );
        $retPayDaifuApply = model('PayDaifuApply')->updateById($payDaifuApply, $resPayDaifuApply->id);
        if($retPayBis && $retPayDaifuApply) {
            return true;
        }
    }
    

        
    /*
     * 代付通知信息
     */
    function callbackDaifuTrue($data, $md5key) {
        $resArr = array(
            'code'          => '1000',
            'msg'           => $data['msg'],
            'merchant_id'   => $data['merchant_id'],  // 商户号
            'mchnt_batchid' => $data['mchnt_batchid'], // 出款批次号
            'mchnt_orderid' => $data['mchnt_orderid'], // 出款订单号
            'amount'        => $data['amount'], // 出款金额 
            'status'        => $data['status'], // 打款状态
            'bank_status'   => $data['bank_status'], // 银行处理状态
            
        );
        // 生成新的签名
        $resArr['signature'] = payChangyuanSign($resArr, $md5key);
        return json_encode($resArr, 320);
    }